package com.example.javaeefinal.controller;

import com.example.javaeefinal.Service.DepartmentService;
import com.example.javaeefinal.Service.Imp.DepartmentImpl;
import com.example.javaeefinal.pojo.Department;
import com.example.javaeefinal.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/dep")
public class DepartmentController {
    @Autowired
    private DepartmentImpl departmentImpl;

    @PostMapping("/addDep")
    @ResponseBody
    public Result<String> addDep(HttpServletRequest request, String departmentName, int principal) {
        departmentImpl.createNewDepartment(departmentName, principal);
        return Result.success();
    }

    @PostMapping("/delDep")
    @ResponseBody
    public Result<String> delDep(HttpServletRequest request, int departmentId) {
        Department dep = departmentImpl.selectDepartmentById(departmentId);
        if (dep != null) {
            departmentImpl.deleteDepartmentById(departmentId);
            return Result.success();
        } else {
            return Result.error("DepIsNull", "没有找到要删除的部门");
        }
    }


    @PostMapping("/getDep")
    @ResponseBody
    public Result<String> getDep(HttpServletRequest request, int departmentId) {
        Department dep = departmentImpl.selectDepartmentById(departmentId);
        if (dep != null) {
            request.getSession().setAttribute("department", dep);
            return Result.success();
        } else {
            return Result.error("DepIsNull", "没有找到该部门");
        }
    }


    @PostMapping("/updateDep")
    @ResponseBody
    public Result<String> updateDep(HttpServletRequest request, String departmentName, int principal, String mail, String address, String code, int departmentId) {
        Department dep = departmentImpl.selectDepartmentById(departmentId);
        if (dep != null) {
            departmentImpl.updateDepartmentById(departmentId, departmentName, principal);
            departmentImpl.updateDepInfoById(departmentId, mail, address, code);
            return Result.success();
        } else {
            return Result.error("DepIsNull", "没有找到要修改的部门");
        }
    }

    @PostMapping("/getAllDep")
    @ResponseBody
    public Result<String> getAllDep(HttpServletRequest request) {
        List<Department> depList = departmentImpl.getAllDepartment();
        if (!depList.isEmpty()) {
            request.getSession().setAttribute("departmentList",depList);
            return Result.success();
        } else {
            return Result.error("DepIsNull", "您的系统没有录入任何部门");
        }


    }


}

